#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace XFGameFramework.EquipmentSystem
{
    public class CustomEquipmentConfigDataIDGUI : CustomPropertyGUI
    {

        public CustomEquipmentConfigDataIDGUI() : base(true) { }


        public override void OnPropertyGUI(SerializedProperty serializedProperty)
        {
 
            EditorGUILayout.LabelField(string.Empty, "装备id(唯一标识,不可重复)", "BoldLabel");
            int id = serializedProperty.intValue;
            EditorGUI.BeginChangeCheck();
            id = EditorGUILayout.DelayedIntField("Id", id);
            if (EditorGUI.EndChangeCheck())
            {
                if (!IsContainID(id))
                {
                    serializedProperty.intValue = id; 

                    serializedProperty.serializedObject.ApplyModifiedProperties();
                     
                    EquipmentConfigData equipmentConfigData = serializedProperty.serializedObject.targetObject as EquipmentConfigData;
                    if (equipmentConfigData != null)
                    {
                        equipmentConfigData.Rename();

                        if(equipmentConfigData.parent != null)
                            equipmentConfigData.parent.ClearCache();
                    } 
                }
                else
                {
                    string message = string.Format("装备id:{0}已被占用,请使用其他数字来作为id!", id);
                    EditorWindow.focusedWindow.ShowNotification(new GUIContent(message));
                }
            }

        }

        public static List<EquipmentsConfig> GetAllEquipmentsConfig()
        {
            List<EquipmentsConfig> allConfigs = new List<EquipmentsConfig>();

            string[] guids = AssetDatabase.FindAssets(string.Format("t:{0}", typeof(EquipmentsConfig).FullName));

            if (guids != null)
            {
                foreach (var item in guids)
                {
                    string assetpath = AssetDatabase.GUIDToAssetPath(item);
                    if (string.IsNullOrEmpty(assetpath))
                        continue;
                    EquipmentsConfig config = AssetDatabase.LoadAssetAtPath<EquipmentsConfig>(assetpath);
                    if (config == null) continue;
                    allConfigs.Add(config);
                }
            }

            return allConfigs;
        }

        // 判断是否有这个id， 判断所有装备配表，id必须唯一
        public static bool IsContainID(int id)
        {
            foreach (var item in GetAllEquipmentsConfig())
            {
                if (item.GetEquipmentConfigData(id) != null)
                    return true;
            }

            return false;
        } 
    }

}

#endif
